
import mongoose from 'mongoose'

const Course = mongoose.model('Course')
const Question = mongoose.model('Question')
const User = mongoose.model('User')

export async function saveQuestion ({email, courseid, topic, content}) {
  // let condition = courseid ? { courseid } : {}
  let author = await User.find({email: email})
  // let course = await Course.find(condition)
  
  let question = new Question({
    authorinfo: author[0]._id,
    courseid,
    topic,
    content
  })

  let data = await question.save()
  
  return {
    data
  }
}

export async function getQuestions ({courseid, page}) {
  page = page || 1
  
  let condition = courseid ? { courseid } : {}

  let data = await Question.find(condition)
    .sort({ 'createdAt': -1 }).limit(10).skip(10*(page-1))
    .populate('authorinfo', '_id email')
    .exec()
   console.log(data) 

  let result = [] 
  data.forEach((item) => {
    let obj = {}
    obj['author'] = item['authorinfo']['email']
    obj['topic'] = item['topic']
    obj['content'] = item['content']
    obj['createdAt'] = item['createdAt']
    result.push(obj)
  })

  let count = await Question.find(condition).count()
  return {
    data: result,
    count
  }
}
